/**
 * 
 */
package com.jrh.common.security;

import java.io.UnsupportedEncodingException;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;

import com.jrh.common.condition.Precondition;
import com.jrh.common.util.NumberUtil;

/**
 * @author shengli.caosl 2012-2-25 下午6:59:12
 */
public class SecurityUtil {

    private static final String PASSWORD_RONDOM = "jirhe";
    private static final String WORD_PREFIX     = "mj";
    private static final int    HASH_BASE_MOD   = 1000000;
    // private static final String ENCODE_CHARSET = System.getProperty("file.encoding") != null ?
    // System.getProperty("file.encoding") : "UTF-8";
    private static final String ENCODE_CHARSET  = "UTF-8";

    public static String getEncryptWord(String param) {
        return DigestUtils.md5Hex(PASSWORD_RONDOM + DigestUtils.md5Hex(param));
    }

    public static boolean validEncryptWord(String source, String encryptedWord) {
        String dest = DigestUtils.md5Hex(PASSWORD_RONDOM + DigestUtils.md5Hex(source));
        return dest.equals(encryptedWord);
    }

    /**
     * 加了摘要
     * 
     * @param word
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String encodeWord(String word) throws UnsupportedEncodingException {
        Precondition.checkNotBlank(word, "The word cannot be blank for encode!");
        word = Base64.encodeBase64String(word.getBytes(ENCODE_CHARSET));
        int wordHash = (word + WORD_PREFIX).hashCode() % HASH_BASE_MOD;
        String wordHashStr = new Integer(wordHash).toString();
        word = wordHashStr.length() + wordHashStr + word;
        return word;
    }

    /**
     * 再要验证
     * 
     * @param word
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String decodeWord(String word) throws UnsupportedEncodingException {
        Precondition.checkNotBlank(word, "The word cannot be blank for decode!");
        int number = NumberUtil.charToInt(word.charAt(0));
        if (number < 1 || number > 9 || word.length() <= number + 1) {
            throw new IllegalArgumentException();
        }
        String wordHashStr = word.substring(1, number + 1);
        word = word.substring(number + 1);
        String realWord = new String(Base64.decodeBase64(word), ENCODE_CHARSET);
        int wordHash = (word + WORD_PREFIX).hashCode() % HASH_BASE_MOD;
        if (!wordHashStr.equals(new Integer(wordHash).toString())) {
            throw new IllegalArgumentException();
        }
        return realWord;
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        System.out.println("草胜利123143413eqrqerwqewrq:wer;");
        String t = encodeWord("草胜利123143413eqrqerwqewrq:wer;");
        System.out.println(t);
        System.out.println(decodeWord(t));
    }
}
